package org.jeecg.modules.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.company.entity.WlhyCompany;
import org.jeecg.modules.company.mapper.WlhyCompanyMapper;
import org.jeecg.modules.company.service.IWlhyCompanyService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

import static org.jeecg.common.constant.WlhyBizConstant.*;

/**
 * @Description: 企业信息
 * @Author: jeecg-boot
 * @Date:   2024-04-11
 * @Version: V1.0
 */
@Service
public class WlhyCompanyServiceImpl extends ServiceImpl<WlhyCompanyMapper, WlhyCompany> implements IWlhyCompanyService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void authCompany(WlhyCompany wlhyCompany) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        WlhyCompany dbCompany =   getCompanyByUserId(loginUser.getId());
        if (null != dbCompany) {
            updateVersionById(new Date(),dbCompany.getId());
        }
        wlhyCompany.setId(null);
        wlhyCompany.setUserPhone(loginUser.getPhone());
        wlhyCompany.setUserId(loginUser.getId());
        wlhyCompany.setAuthStatus(COMPANY_AUTH_STATUS0);
        wlhyCompany.setStatus(ROW_STATUS1);
        wlhyCompany.setVersion(MAX_DATE);
        save(wlhyCompany);


    }

    private void updateVersionById(Date expireDate, String id) {
        update(new LambdaUpdateWrapper<WlhyCompany>().eq(WlhyCompany::getId,id).set(WlhyCompany::getVersion,expireDate));
    }

    @Override
    public WlhyCompany getCompanyByUserId(String userId) {
        return getOne(new LambdaQueryWrapper<WlhyCompany>()
                .eq(WlhyCompany::getUserId,userId)
                .eq(WlhyCompany::getVersion,MAX_DATE)
        ) ;
    }

    @Override
    public WlhyCompany info() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return getCompanyByUserId(loginUser.getId());
    }

}
